package com.sxau.plantingstructuretuning.model.utils;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ExcelUtil {

    public static Map<String, Object> parseExcel(MultipartFile file) throws Exception {
        Map<String, Object> result = new HashMap<>();

        try (InputStream inputStream = file.getInputStream()) {
            Workbook workbook;

            // 判断文件类型
            String fileName = file.getOriginalFilename();
            if (fileName.endsWith(".xls")) {
                workbook = new HSSFWorkbook(inputStream);
            } else if (fileName.endsWith(".xlsx")) {
                workbook = new XSSFWorkbook(inputStream);
            } else {
                throw new IllegalArgumentException("不支持的文件类型");
            }

            Sheet sheet = workbook.getSheetAt(0);

            List<String> headers = new ArrayList<>();
            List<List<String>> rows = new ArrayList<>();

            for (Row row : sheet) {
                List<String> rowData = new ArrayList<>();
                for (Cell cell : row) {
                    switch (cell.getCellType()) {
                        case STRING:
                            rowData.add(cell.getStringCellValue());
                            break;
                        case NUMERIC:
                            rowData.add(String.valueOf(cell.getNumericCellValue()));
                            break;
                        case BOOLEAN:
                            rowData.add(String.valueOf(cell.getBooleanCellValue()));
                            break;
                        default:
                            rowData.add("");
                    }
                }

                if (row.getRowNum() == 0) {
                    headers = rowData;
                } else {
                    rows.add(rowData);
                }
            }

            result.put("headers", headers);
            result.put("rows", rows);
        }

        return result;
    }
}